# -*- coding: utf-8 -*-
import re
import urllib
import logging

def handleRequestURL(keys, request_url, dealwith='json'):
    a = isinstance(request_url, unicode)
    if a:
        try:
            request_url = unicode(request_url, "utf-8")
        except:
            request_url = unicode(request_url, "gb2312")
#        raise "a is unicode:%s" % str(request_url)
    else:
        try:
            request_url = urllib.unquote(request_url.decode("utf-8").encode("utf-8"))
        except:
            pass
#            request_url = urllib.unquote(request_url.decode("gb2312").encode("gb2312"))
#        raise "a is not unicode:%s" % str(request_url)
#    raise str(request_url)
    if dealwith == 'json':
        dict = {}
        dict.update({"size": [300, 500]})
        dict.update({"type": "line"})
        dict.update({"labels": []})
        dict.update({"alt": "#YValue"})
        dict.update({"title": ""})
        dict.update({"view3d": "false"})
        for key in keys:
            dict.update(handleParam(key, request_url))
        datas = dict["datas"]
        labels = dict["labels"]
        diff = datas.__len__() - labels.__len__()
        if diff > 0:
            for i in range(diff):
                labels.append(" ")
        
#        for data_dict in datas:
#            try:
#                type = data_dict["type"]
#            except KeyError:
#                data_dict.update({"type": dict["type"]})
#            data = data_dict["data_list"]
#            data = zip(data, labels)
#            data_dict["data_list"] = data
#            raise str(data)
#        raise str(datas)
#        datas = zip(datas, labels)
#        raise str(datas)
        dict.update({"datas": datas})
        return dict
    else:
        list = []
        for key in keys:
            result = handleParam(key, request_url, dealwith)
            if isinstance(result, unicode):
                result = result.decode("utf-8").encode("utf-8")
#                raise "result is unicode: %s" % str(result)
            else:
                try:
                    result = result.decode("utf-8").encode("utf-8")
                except:
                    result = result.decode("gb18030").encode("utf-8")
            
            list.append(result)
#        raise str(list)
#        list = [i.decode("utf-8").encode("gb2312") for i in list]
        result_url = "&".join(list)
        return result_url


def handleParam(key, request_url, dealwith='json'):
#    raise str(a)
    request_list = request_url.split("&")
    dict = {}
    for req in request_list:
        try:
            dict[req.split("=")[0]] = req.split("=")[1]
        except IndexError:
            pass
    return {
        "datas":  lambda request_url, dealwith: handleDatas(dict[key], dealwith),
        "labels": lambda request_url, dealwith: handleLabels(dict[key], dealwith),
        "type":   lambda request_url, dealwith: handleType(dict[key], dealwith),
        "alt":    lambda request_url, dealwith: handleAlt(dict[key], dealwith),
        "size":   lambda request_url, dealwith: handleSize(dict[key], dealwith),
        "title":  lambda request_url, dealwith: handleTitle(dict[key], dealwith),
        "view3d": lambda request_url, dealwith: handleView3d(dict[key], dealwith)
    }[key](dict[key], dealwith)


def handleDatas(params, dealwith='json'):
    params = urllib.unquote(params)
    pattern_combination = r"\w+:[\d+(.\d+),|]+"
    pattern_common      = r"[\d+(.\d+),]+"

    try:
        datas = re.compile(pattern_combination).search(params).group()
        params = re.sub(r"[+]", "", params)
        all_list = re.findall(r"\w+:[\d+(.\d+),|]+", params)
        data_list = []
        for p in all_list:
            datas = p.split(":")[1]
            core_datas = datas.split("|")
            for core_data in core_datas:
                data = core_data.split("^")
                data_list.append(data)
    except:
        datas = re.compile(pattern_common).search(params).group()
        datas = map(int, datas.split(","))
        return {"datas": datas}
    return {"datas": data_list}


def handleLabels(params, dealwith='json'):
    params = urllib.unquote(params)
    if dealwith == 'json':
        patterns = ".*"
        p = re.compile(patterns)
        labels = p.search(params).group()
        labels = labels.split("|")
        return {"labels": labels}
    else:
        patterns_labels = ".*"
        p_labels = re.compile(patterns_labels)
        try:
            url_labels = p_labels.search(params).group()
            url_labels = re.sub(",", "|", url_labels)
            url_labels = re.sub(":", "|", url_labels)
            params = re.sub(patterns_labels, url_labels, params)
        except:
            return "labels="
        return "labels=%s" % params


def handleType(params, dealwith='json'):
#    try:
#        params = urllib.unquote(params).decode('gb2312')
#    except:
#        params = urllib.unquote(params).decode('utf-8')
#    else:
#        params = urllib.unquote(params)
#    url_type = re.compile("type=[\S:]+").search(request_url).group()
    type = re.compile("[\\w]+").search(params).group()
    if dealwith == 'json':
        return {"type": type}
    else:
        return "type=%s" % type


def handleAlt(params, dealwith='json'):
    params = urllib.unquote(params)
    if dealwith == 'json':
    #    alt = re.compile("[\\S+]+").search(params).group()
        params = re.sub("\[x\]", "#AxisXLabel", params)
        params = re.sub("\[y\]", "#YValue", params)
        params = re.sub("\[X\]", "#AxisXLabel", params)
        params = re.sub("\[Y\]", "#YValue", params)
        
        params = urllib.unquote(params)#.decode('gb2312')
        return {"alt": params}
    else:
        patterns_alt = ".*"
        p_alt = re.compile(patterns_alt)
        substr = '，'
    #    substr = urllib.unquote(substr).decode('utf-8')
        try:
            url_alt = p_alt.search(params).group()
            url_alt = re.sub(",", substr, url_alt)
            params = re.sub(patterns_alt, url_alt, params)
        except:
            return "alt="
        return "alt=%s" % params


def handleSize(params, dealwith='json'):
    patterns = "(\d{1,3})x(\d{1,3})"
    p = re.compile(patterns)
    try:
        size = p.search(params).group()
        size = size.split("x")
    except:
        return ""
    return {"size": size, "width": size[0], "height": size[1]}


def handleTitle(params, dealwith='json'):
    params = urllib.unquote(params)
#    raise params
    patterns = ".*"
    p = re.compile(patterns)
    if dealwith == 'json':
        try:
            title = p.search(params).group()
        except:
            return {"title": "chart title"}
#        title = urllib.unquote(title).decode('utf-8').encode("utf-8")
        return {"title": title}
    else:
#        try:
#            params = params.decode("utf-8")
#        except:
#            params = params.decode("gb18030")
#        raise str(params.encode("utf-8"))
        try:
            title = p.search(params).group()
        except:
            return ""
        return "title=%s" % title


def handleView3d(params, dealwith='json'):
    patterns = "true|false"
    p = re.compile(patterns)
    if dealwith == 'json':
        try:
            view3d = p.search(params).group()
        except:
            return {"view3d": "false"}
        return {"view3d": view3d}
    else:
        try:
            view3d = p.search(params).group()
        except:
            return "view3d=false"
        return "view3d=%s" % view3d


def handlerNone(params, dealwith='json'):
    return {"datas": [], "type": "line", "alt": "#YValue"}
